package server;

import game.SuperGame;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

import player.Player;

public class Referee implements Runnable {

	SuperGame game = null;
	BufferedReader bufIn = null;
	ServerSocket socketServer = null;
	Socket clientSocket = null;
	InputStream in;

	public Referee(SuperGame sg) {
		this.game = sg;
	}

	// send message to the player
	public void sendMsg(String msg, BufferedWriter bufOut) {
		try {
			bufOut.write(msg);
			bufOut.newLine();
			bufOut.flush();
		} catch (IOException e) {
			System.out
					.println("An error has been occured while sending the message to the player");
			e.printStackTrace();
		}
	}

	// server thread
	public void run() {
		// this part make all of party gamer's connect to socket
		try {
			// create a new referee's socket
			// players will connect to this new referee
			socketServer = new ServerSocket(0);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		int localPort = socketServer.getLocalPort();
		// send new address to every player of the game
		for (Player p : game.getListPlayer()) {
			sendMsg(localPort + "-ip", p.getBufOut());
			try {
				// wait for the player to connect
				this.clientSocket = socketServer.accept();

				// set writers and readers with the new socket
				p.setBufOut(clientSocket);
				p.setBufIn(clientSocket);

				// launch a listening thread associated to this game
				new Thread(new ThreadListentPlayer(clientSocket, this.game))
						.start();

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		// ---------------------------------------------------------------

		// inform the players that their opponent has been found
		for (Player p : game.getListPlayer()) {
			for (Player pl : game.getListPlayer()) {
				if (!pl.getPseudo().equals(p.getPseudo())) {
					sendMsg(pl.getUdpServerAddress() + "_"
							+ pl.getUdpServerPort() + "_udpAdr", p.getBufOut());
				}
			}

		}
		for (Player p : game.getListPlayer()) {
			sendMsg("opponentFound", p.getBufOut());
		}

		// while the game isn't over
		while (!game.isGameOver()) {

		}
	}
}
